package com.only4play.authcenter.v2.security.authentication.admin.password;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @author hinzzz www.hinzzz.cn 157957329@qq.com
 * 2024-04-08
 */
public class AdminPasswordLoginConfigurer extends AbstractHttpConfigurer<AdminPasswordLoginConfigurer, HttpSecurity> {

    @Override
    public void init(HttpSecurity builder) throws Exception {
        super.init(builder);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        ApplicationContext applicationContext = http.getSharedObject(ApplicationContext.class);
        AuthenticationManagerBuilder builder = http.getSharedObject(AuthenticationManagerBuilder.class);
        AdminPasswordLoginProcessFilter adminPasswordLoginProcessFilter = new AdminPasswordLoginProcessFilter(builder.getObject());
        AuthenticationSuccessHandler authenticationSuccessHandler = applicationContext.getBean(AuthenticationSuccessHandler.class);
        AuthenticationFailureHandler authenticationFailureHandler = applicationContext.getBean(AuthenticationFailureHandler.class);

        adminPasswordLoginProcessFilter.setAuthenticationSuccessHandler(authenticationSuccessHandler);
        adminPasswordLoginProcessFilter.setAuthenticationFailureHandler(authenticationFailureHandler);
        http.addFilterBefore(adminPasswordLoginProcessFilter, AdminPasswordLoginProcessFilter.class);


        super.configure(http);
    }

    @Bean
    public static AdminPasswordLoginConfigurer adminPasswordLoginConfigurer() {
        return new AdminPasswordLoginConfigurer();
    }
}
